/*
 * Copyright (c) 2025 UCT Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

import { BusinessError, deviceInfo } from '@kit.BasicServicesKit';
import { common, StartOptions, Want, bundleManager } from '@kit.AbilityKit';
import { _TableName_TitleView, Cloud_TableName_ListView } from 'commondb';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { CommonConstants } from 'commondb';
import { _table_name_, _TableName_Response, getDB } from 'commondb';
import axios, {AxiosError, AxiosResponse, AxiosProgressEvent, InternalAxiosRequestConfig, AxiosRequestConfig} from '@ohos/axios'

@Entry
@ComponentV2
export struct Cloud_TableName_ListPage {
  private context = getContext(this) as common.UIAbilityContext;
  @Provider() _table_name_List: _table_name_[] =  [new _table_name_()];
  private bundleName: string = '';

  async aboutToAppear() {
    let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT;
    try {
      bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => {
        this.bundleName = data.name;
        hilog.info(0x0000, 'testTag', 'getBundleInfoForSelf successfully. Data: %{public}s', JSON.stringify(data));
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed. Cause: %{public}s', err.message);
      });
    } catch (err) {
      let message = (err as BusinessError).message;
      hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', message);
    }

    const access_token = AppStorage.get<string>('access_token')
    if(!access_token){  //没有登录态，访问云数据库需要先登录，跳转登录页
      this.getUIContext().showAlertDialog(
        {
          title: $r('app.string.login'),
          message: $r('app.string.login_message'),
          autoCancel: true,
          alignment: DialogAlignment.Bottom,
          offset: { dx: 0, dy: -20 },
          gridCount: 3,
          confirm: {
            value: $r('app.string.go_to_login'),
            action: () => {
              let want: Want = {
                bundleName: this.bundleName,
                abilityName: 'LoginAbility'
              };
              let option: StartOptions = { displayId: CommonConstants.COMMON_ZERO };
              this.context.startAbility(want, option);
            }
          },
          cancel: () => {

          }
        }
      );
    }else{
      const result = await _table_name_.apiGet_TableName_List(  //服务端API需登录鉴权token，登陆后可获取到返回值
        0,
        10,
        ''
      );
      if (result) {
        const rawResponse = result.getRawResponse() as AxiosResponse<_TableName_Response, Record<string, never>>
        this._table_name_List = rawResponse.data._table_name_s.map(item => _table_name_.fromJson(JSON.stringify(item)));
      }
    }
  }

  async onPageShow() {
  }

  build() {
    Column() {
      _TableName_TitleView();
      Cloud_TableName_ListView();
    }
    .height('100%')
    .width('100%')
    .alignItems(HorizontalAlign.Start)
    .margin({ left: 15 })
  }
}